<template>
    <el-container>
        <el-header style="text-align: right; font-size: 15px" height="50px">
            <el-row type="flex" justify="end">
                <el-col :xs="0" :sm="0" :md="10" :lg="14" :xl="14">
                    <h4 style="text-align: center">{{current_period?current_period.name:''}} 员工住宿费用表</h4>
                </el-col>
                <el-col :xs="0" :sm="8" :md="8" :lg="4" :xl="4">
                    <el-input
                            v-model="search"
                            size="medium"
                            placeholder="输入宿舍楼关键字搜索"/>
                </el-col>
                <el-col :xs="22" :sm="14" :md="4" :lg="4" :xl="4">
                    <el-dropdown size="medium" split-button type="primary" trigger="click" @command="handleCommand">
                        <i class="fa fa-bars"></i>
                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item command="init">初始化水电表读数</el-dropdown-item>
                            <el-dropdown-item command="exportFees">导出费用列表</el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                </el-col>
            </el-row>
        </el-header>
        <el-table
                id="feeTable"
                v-loading="loading"
                element-loading-text="拼命加载中"
                element-loading-spinner="el-icon-loading"
                element-loading-background="rgba(0, 0, 0, 0.8)"
                style="width: 100%"
                :data="period_record.filter(data => !search || data.buildingName.toLowerCase().includes(search.toLowerCase()))"
                height="800px" row-class-name="myRowStyle">
            <el-table-column prop="staffName" label="姓名" width="120" sortable>
            </el-table-column>
            <el-table-column prop="staffIdCard" label="身份证" width="250" sortable>
            </el-table-column>
            <el-table-column prop="departmentName" label="部门">
            </el-table-column>
            <el-table-column prop="buildingName" label="宿舍楼">
            </el-table-column>
            <el-table-column prop="dormCode" label="房号" sortable>
            </el-table-column>
            <el-table-column prop="waterFee" label="水费" sortable>
            </el-table-column>
            <el-table-column prop="electricFee" label="电费" sortable>
            </el-table-column>
            <el-table-column prop="dormFee" label="住宿费" sortable>
            </el-table-column>
            <el-table-column label="合计" sortable>
                <template slot-scope="scope">
                    <span>{{Number.parseFloat(scope.row.waterFee)+Number.parseFloat(scope.row.electricFee)+Number.parseFloat(scope.row.dormFee)}}</span>
                </template>
            </el-table-column>
        </el-table>
        <router-view></router-view>
        <el-dialog :visible.sync="initDialogVisible" width="40%">
            <el-form>
                <el-form-item label="导入初始化文件" label-width="120px">
                    <el-input id="initFile" type="file" @change="fileChanged"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="initDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="confirmImportData">确 定</el-button>
            </div>
        </el-dialog>
        <el-dialog title="要导入的初始化数据" :visible.sync="dataDialogVisible">
            <el-table :data="importedData" height="500px">
                <el-table-column property="dorm_id" label="ID" sortable></el-table-column>
                <el-table-column property="building_name" label="宿舍楼" sortable></el-table-column>
                <el-table-column property="dorm_code" label="宿舍号" sortable></el-table-column>
                <el-table-column property="water_reading" label="水表读数" width="150"></el-table-column>
                <el-table-column property="electric_reading" label="电表读数" width="200"></el-table-column>
                <el-table-column property="record_date" label="抄表日期" width="200"></el-table-column>
            </el-table>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dataDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="importData">导入</el-button>
            </div>
        </el-dialog>
    </el-container>
</template>
<script>
    import FileSaver from 'file-saver'
    import XLSX from 'xlsx'
    export default{
        props: ['period_id'],
        data(){
            return {
                period_record: [],
                loading: false,
                search: '',
                initDialogVisible: false,
                dataDialogVisible: false,
                importedData: [],
                current_period:{}
            }
        },
        created(){
            this.getPeriodRec(this.period_id);
        },
        watch: {
            'period_id': function (to, from) {
                this.getPeriodRec(to);
            }
        },
        methods: {
            getPeriodRec(period_id){
                this.$emit('emitindex');//解决人为刷新页面时，默认选中宿舍菜单失去焦点
                axios.get('api/v1/dormMeterRecordFee?period_id=' + this.period_id).then(result => {
                    this.period_record = result.data;

                });
                axios.get('api/v1/period/'+period_id).then(result=>{
                    this.current_period=result.data;
                });
            },
            exportFees () {
                const loading = this.$loading({
                    lock: true,
                    text: '正在导出',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.7)'
                });
                /* generate workbook object from table */
                let wb = XLSX.utils.table_to_book(document.querySelector('#feeTable'), {raw: true});
                let ws = wb.Sheets['Sheet1'];
                var range = XLSX.utils.decode_range('F2:I' + (this.period_record.length + 1));
                for (var R = range.s.r; R <= range.e.r; ++R) {
                    for (var C = range.s.c; C <= range.e.c; ++C) {
                        var cell_address = {c: C, r: R};
                        /* if an A1-style address is needed, encode the address */
                        var cell_ref = XLSX.utils.encode_cell(cell_address);
                        ws[cell_ref].t = 'n';
                    }
                }
                /* get binary string as output */
                let wbout = XLSX.write(wb, {bookType: 'xlsx', bookSST: true, type: 'array'});
                try {
                    FileSaver.saveAs(new Blob([wbout], {type: 'application/octet-stream'}), 'fee.xlsx');
                } catch (e) {
                    if (typeof console !== 'undefined')
                        console.log(e, wbout)
                }
                loading.close();
            },
            importData(){
                var data = Array.from(this.importedData,d=>_.omit(d,['building_name','dorm_code']));
                console.log(data);
                axios.post('api/v1/dormMeterRecord/init/'+this.period_id,data).then(result=>{
                    this.$notify.success({message:'初始化数据导入成功'});
                    this.initDialogVisible = false;
                }).catch(error=>{
                    if(error.response){
                        console.log(error.response);
                    }
                    this.$notify.error({message:'初始化数据导入异常，请联系系统开发人员处理'});
                });
                this.initDialogVisible = false;

            },
            handleCommand(cmd){
                switch (cmd) {
                    case 'init':
                        this.initDialogVisible = true;
                        break;
                    case 'exportFees':
                        this.exportFees();
                        break;
                    case 'exportDorms':
                        this.exportDorms();
                        break;
                }
            },
            fileChanged(){
                var f = document.querySelector('#initFile').files[0];
                var reader = new FileReader();
                var result = [];
                reader.onload = function (e) {
                    if (typeof console !== 'undefined') console.log("onload");
                    var data = e.target.result;
                    var workbook = XLSX.read(data, {type: 'binary',cellDates:true, cellNF: false, cellText:false});
                    workbook.SheetNames.forEach(function (sheetName) {
                        var ws = workbook.Sheets[sheetName];
                        if (ws['C1'].v == '宿舍号' && ws['D1'].v == '水表读数' && ws['E1'].v == '电表读数') {
                            ws['A1'] = {v: 'dorm_id', t: 'n'};
                            ws['B1'] = {v: 'building_name', t: 's'};
                            ws['C1'] = {v: 'dorm_code', t: 'n'};
                            ws['D1'] = {v: 'water_reading', t: 'n'};
                            ws['E1'] = {v: 'electric_reading', t: 'n'};
                            ws['F1'] = {v: 'record_date', t: 'd'};
                            var roa = XLSX.utils.sheet_to_json(ws, {raw:false,header: 0,dateNF:'YYYY-MM-DD'});
                            if (roa.length) {
                                result = _.concat(result, Object.values(roa));
                            }
                        }
                    });
                    window.importedData = result;
                };
                reader.readAsBinaryString(f);//rABS 读取二进制字符串,

            },
            confirmImportData(){
                this.importedData = _.concat(this.importedData, window.importedData);
                if(this.importedData.length>0){
                    this.initDialogVisible = false;
                    window.importedData = [];
                    this.dataDialogVisible = true;
                }else{
                    this.$alert('使用的导入excel模板不正确或者excel文件中没有数据');
                }
            }
        }
    }
</script>
